import dayjs from "dayjs";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
// import { getOnlineLogsList } from "@/apiOld/system";
import { reactive, ref, onMounted, computed } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import { callOrder_listByStaff,outbound_list,callOrder_toGain } from "@/api/outbound"
import { callLogList } from "@/api/customer";
import { useUserStoreHook } from "@/store/modules/user";
import { getUser } from "@/api/user"

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_search_task: false, // 群呼任务
    is_search_intension: false, // 客户状态
    is_search_phone: false, // 电话号码
    is_search_gain: false, // 领取状态
    is_search_createAt: false, // 创建时间

    is_callOrder_gain: false, // 添加到我的领取客户
  })

  const shortcuts = [
    {
      text: "上周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        return [start, end];
      }
    },
    {
      text: "上个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        return [start, end];
      }
    },
    {
      text: "三个月前",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        return [start, end];
      }
    }
  ];
  const form = reactive({
    orderType:"outboundCall",
    project: "",
    sourceId: "",
    rangeTime: "",
    status: "",
    phone: "",
    duration: "",
    isGain:"" // 领取状态
  });
  const dataList = ref([]);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    currentPage: 1,
    background: true
  });
  const columns= reactive<TableColumnList>([
    {
      label: "法人名称",
      prop: "company_name",
      minWidth: 120
    },
    {
      label: "被叫号码",
      prop: "phone",
      minWidth: 130
    },
    // {
    //   label: "归属地",
    //   prop: "numberArea",
    //   minWidth: 150
    // },
    {
      label: "拨打时间",
      prop: "createtime",
      minWidth: 160,
      formatter: ({ createtime }) =>{
        return dayjs.unix(createtime).format("YYYY-MM-DD HH:mm:ss")
      }
        
    },
    {
      label: "应答时长（秒）",
      prop: "callTime",
      minWidth: 80,
      formatter: ({ callTime }) =>{
          if(callTime==0){
            return 0;
          }else{
            return Math.floor(callTime/1000);
          }
      }
    },
    {
      label: "呼叫结果",
      prop: "status",
      minWidth: 130,
      formatter: ({ status }) =>{
        if(status == 3){
          return "接通";
        }else if(status == 4){
          return "来电拒接或未接听";
        }else if(status == 5){
          return "对方拒接或未接听";
        }else if(status == 6){
          return "通话中时来电占线";
        }
      }
    },
    {
      label: "客户状态",
      prop: "intension",
      minWidth: 130,
      formatter: ({ intension }) =>{
        let map={
          'unknown':'接通未确定',
          'refuse':'无意向',
          'intend':'有意向',
          '':'未确定'
        };
        return map[intension];
      }
    },
    {
      label: "领取状态",
      prop: "gain",
      minWidth: 150,
      formatter: ({gain }) =>{
        let map={
          '1':'已领取',
          '0':'未领取'
        };
        return map[gain];
      }
    },
    {
      label: "通话录音",
      slot: "record",
      minWidth: 150,
    },
  ]);

  // 添加到我的领取客户
  function addClick() {
    ElMessageBox.confirm(
      "确定执行该操作？",
      "重要提示",
      {
        type: "warning"
      }
    )
      .then(() => {
        let arr = [];
        multipleSelection.value.map(item=>{
        arr.push( item.callId  )
        })
        // console.log(arr)
        callOrder_toGain({
          callIds : arr.join(",")
        }).then(res=>{
          if(res.code == 1000){
            message(`领取成功`, { type: "success" });
          }
        })
      })
      .catch(() => {});
  }

  const tableRef = ref();
  const multipleSelection = ref([]);

  function handleSizeChange(val: number) {
    pagination.pageSize=val;
    dataList.value = []
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage=val;
    dataList.value = []
    onSearch();
  }

  function handleSelectionChange(val) {
    multipleSelection.value = val;
  }

  function handleSelectionClear() {
    const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
    clearSelection();
  }

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    // const { data } = await getOnlineLogsList(toRaw(form));
    // dataList.value = data.list;
    // pagination.total = data.total;
    // pagination.pageSize = data.pageSize;
    // pagination.currentPage = data.currentPage;
    getUser().then(res=>{
      if(res.code == 1000){
        callLogList({
      size:pagination.pageSize,
      page:pagination.currentPage,
      keyword: form.phone,
      staff_id:res.data.id
    }).then(res=>{
      if(res.code == 1000){
        loading.value = false;
        pagination.total = res.data.total
        dataList.value = res.data.data
      }
    })
      }
    })
    

    // setTimeout(() => {
    //   loading.value = false;
    // }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  const taskList = ref([])
  /** 获取群呼任务 */
  function getCallTask(){
    outbound_list().then(res=>{
      if(res.code == 1000){
        taskList.value = res.data.list
      }
    })
  }


  onMounted(() => {
    onSearch();
    // getCallTask();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/groupcallTask/customerStatement/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/groupcallTask/customerStatement/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);

      // callOrderStaff_table
      if (homeDataObj.callOrderStaff_table) {
        // search
        if (homeDataObj.callOrderStaff_table.search && homeDataObj.callOrderStaff_table.search.length) {
          let permiss = homeDataObj.callOrderStaff_table.search.join(',')
          permissions.is_search_task = permiss.includes('task') ? true : false
          permissions.is_search_intension = permiss.includes('intension') ? true : false
          permissions.is_search_phone = permiss.includes('phone') ? true : false
          permissions.is_search_gain = permiss.includes('gain') ? true : false
          permissions.is_search_createAt = permiss.includes('createAt') ? true : false
        }
        // batch
        if (homeDataObj.callOrderStaff_table.batch && homeDataObj.callOrderStaff_table.batch.length) {
          let permiss = homeDataObj.callOrderStaff_table.batch.join(',')
          permissions.is_callOrder_gain = permiss.includes('callOrder_gain') ? true : false
        }

        let tableRemove = homeDataObj.callOrderStaff_table.remove ? homeDataObj.callOrderStaff_table.remove.split(',') : []
        for (let i = 0; i < tableRemove.length; i++) {
          for (let a = 0; a < columns.length; a++) {
            if (columns[a].prop == tableRemove[i]) {
              columns.splice(a, 1)
            }
          }
        }
      }
    }
  });

  return {
    permissions,

    shortcuts,
    form,
    loading,
    columns,
    dataList,
    pagination,
    tableRef,
    multipleSelection,
    taskList,

    addClick,

    onSearch,
    resetForm,
    handleOffline,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    handleSelectionClear
  };
}
